package com.zxjbyte.yiyi.module.system.manager;

import cn.hutool.core.util.StrUtil;
import com.zxjbyte.yiyi.framework.common.util.CollXUtil;
import com.zxjbyte.yiyi.module.system.domain.entity.DevConfigPO;
import com.zxjbyte.yiyi.module.system.service.DevConfigService;
import com.zxjbyte.yiyi.module.system.util.cache.DevConfigCacheUtil;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统开发配置管理器
 *
 * @Author zhangxingjia
 * @Date 2024/9/12 14:13
 * @Version: 1.0
 */
@Component
public class DevConfigManager {

    private static DevConfigManager instance;
    @Resource
    private DevConfigService devConfigService;

    /**
     * 根据配置键获取配置值
     * @param configKey
     * @return
     */
    public String getConfigValue(String configKey){
        DevConfigPO devConfigPo = devConfigService.getByConfigKey(configKey);
        if(devConfigPo == null){
            return null;
        }
        return devConfigPo.getConfigValue();
    }

    /**
     * 重新加载系统配置
     *
     * @param configKey
     */
    public void reload(String configKey){
        if(StrUtil.isNotEmpty(configKey)){
            String configValue = getConfigValue(configKey);
            if(configValue != null){
                DevConfigCacheUtil.put(configKey, configValue);
            }
        } else {
            List<DevConfigPO> list = devConfigService.list();
            if(CollXUtil.isNotEmpty(list)){
                Map<String, String> map = list.stream().collect(Collectors.toMap(DevConfigPO::getConfigKey, DevConfigPO::getConfigValue));
                DevConfigCacheUtil.putAll(map);
            }
        }
    }


    @PostConstruct
    public void init() {
        instance = this;
    }

    public static DevConfigManager getInstance() {
        if (instance == null) {
            throw new IllegalStateException("DevConfigManager not initialized yet");
        }
        return instance;
    }
}
